#include<iostream>
#include"../comm/httplib.h"
#include"oj_control.hpp"
#include<signal.h>
using namespace httplib;
using namespace ns_control;

static Control *ctrl_ptr = nullptr;
void Recovery(int signal)
{
    ctrl_ptr->RecoveryMachine();
}
int main()
{
    signal(SIGQUIT,Recovery);
    //用户请求的服务器路由功能
    Server svr;
    Control ctrl;
    ctrl_ptr = &ctrl;
    //获取所有的题目列表
    svr.Get("/all_questions",[&ctrl](const Request &req,Response &resp)
    {
        //返回一张包含所有题目的html网页
        std::string html;
        ctrl.AllQuestions(&html);
        resp.set_content(html,"text/html;charset=utf-8");
        //resp.set_content("这是所有的题目列表","test/plain;charset=utf-8");
    });
    //根据题目列表，选择题号，获取题目内容
    svr.Get(R"(/question/(\d+))",[&ctrl](const Request &req,Response &resp)
    {
        std::string number = req.matches[1];
        std::string html;
        ctrl.Question(number,&html);
        resp.set_content(html + number,"text/html;charset=utf-8");
    }); 
    //用户提交代码，判题功能（1.测试用例 2.complile_and_run）
    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request &req, Response &resp){
        std::string number = req.matches[1];
        // std::cout << "Received POST request for judge with number: " << number << std::endl;  
        // std::cout << "Request body: " << req.body << std::endl;
        std::string result_json;
        ctrl.Judge(number, req.body, &result_json);
        resp.set_content(result_json, "application/json;charset=utf-8");
        // resp.set_content("指定题目的判题: " + number, "text/plain; charset=utf-8");
    });
    svr.set_base_dir("./wwwroot");
    svr.listen("0.0.0.0",8080);
    return 0;
}

// #include <iostream>  
// #include <fstream>  
// #include <string>  
  
// int main() {  
//     std::ifstream inputFile; // 打开文件  
//     inputFile.open("./conf/service_machine.conf");
  
//     if (!inputFile.is_open()) { // 检查文件是否成功打开  
//         std::cerr << "无法打开文件！\n";  
//         return 1;  
//     }  
  
//     std::string line;  
//     while (std::getline(inputFile, line)) { // 逐行读取文件  
//         std::cout << line << '\n'; // 将每一行输出到控制台  
//     }  
  
//     inputFile.close(); // 关闭文件  
//     return 0;  
// }